package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.beans.History;
import com.eryos.android.cigarettecounter.database.CigaretteDatabase;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public abstract class RootActivity extends Activity  {
	
	/** *************** Static Variables *************** **/	
	
	public static final String PREFS_NAME 					= "eryos-config";
	public static final String SDCARD_NAME 					= "cigarettecounter.csv";

	protected static CigaretteDatabase db;

	private static CigaretteCounter home;
	private static ProgressDialog waitingDialog;
	private static View rootView = null;
	
	private static final String GOOGLE_ANALYTICS_TRACKER_ID = "UA-8541799-7";
		
	/** *************** Instance Variables *************** **/	
    
	private GoogleAnalyticsTracker tracker = GoogleAnalyticsTracker.getInstance();

	protected Menu menu;

	public enum HISTO{WEEKLY, MONTHLY};
	public enum VIEW{HOME, WEEKLY, MONTHLY, SETTINGS};

	private Handler mHandler = new Handler();
	
	private Runnable initValuesComplete = new Runnable(){
		public void run(){
			/* Update the UI with values retrieved/calculated by initValues() */				
			updateUI();
			
			/* dismiss the splash screen created after initUI() */
			hideWaitingMessage();
		}
	};
	
	/** *************** *********** *************** **/
	
    /** 
     * Called when the activity is first created. 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(getLocalClassName(), "onCreate");
        
        

        if ( this instanceof CigaretteCounter ){
        	if ( rootView == null )
        		rootView = getWindow().getDecorView();
        	if ( home != null )
        		home.finish();
        	
        	home = (CigaretteCounter) this;        	
        }
        
        /* Init Ads and Stats Tracker */
        manageAdsAndStats();
        
		/* Init and open the DB connection */
		initDB();
		
		/* Init UI elements */
		initUI();
		
		/* Init UI Handlers */
		initHandlers();
		
		/* show splashscreen during complex treatment */
		showWaitingMessage();
		
		/* Process long/complex treatments in separate thread */
		Thread t = new Thread(){
			public void run(){
				/* Init values ( from DB, Network, etc. ) */
				initValues();
				
				/* stop this thread and return to the main thread */
				mHandler.post(initValuesComplete);
			}
		};	
		t.start();
    }

    /**
     * Method used to initialize the DB connection
     */
    private void initDB(){
    	if ( db == null ){
    		db = new CigaretteDatabase(this);        
    		db.open();
    	}
    }
    
    /**
     * Method used to handle Ads part and Tracker item
     */
    private void manageAdsAndStats(){
    	tracker.start(GOOGLE_ANALYTICS_TRACKER_ID, this);
    	
    	//AdManager.setTestDevices( new String[] { AdManager.TEST_EMULATOR } );        
    }

    /**
     * Init all UI elements
     */
    protected abstract void initUI();
	
    /**
	 * Method used to defined all UI handlers
	 */
    protected abstract void initHandlers();

    /**
     * init Values ( not UI ) for this activiry from DB / Network / etc.
     */
    protected abstract void initValues();
    
    /**
     * Method used to update the UI after called to initValues()
     */
    public abstract void updateUI();
    
    /**
     * Override onCreateOptionsMenu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	this.menu = menu;
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        
        return true;
    }

	/**
	 * Override onOptionsItemSelected
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case R.id.home:
        	showView(VIEW.HOME);
            return true;
        case R.id.param:
        	showView(VIEW.SETTINGS);
            return true;
        default:
        	return false;
        }
    }
    
    /**
     * Method used to display another view ( Home, Stats, Settings )
     * @param _view : the new view to display
     */
    public void showView(VIEW _view){
    	Class dest = this.getClass();
    	History typeHisto = new History(History.Type.WEEKLY);
    	switch(_view){
    	case HOME:
    		dest = CigaretteCounter.class;
    		break;
    	case WEEKLY:
    		dest = HistoryActivity.class;
    		typeHisto = new History(History.Type.WEEKLY);
    		break;
    	case MONTHLY:
    		dest = HistoryActivity.class;
    		typeHisto = new History(History.Type.MONTHLY);
    		break;
    	case SETTINGS:
    		dest = ConfigActivity.class;
    		break;
    	}

    	Intent intent = new Intent(RootActivity.this, dest);
    	intent.putExtra(History.class.toString(), typeHisto);
    	startActivity(intent);

    	if ( ! (this instanceof CigaretteCounter) )
    		finish();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	Log.d(getLocalClassName(), "onResume");
    	db.open();
    }
    
    @Override
    public void onStart() {
    	super.onStart();
        Log.d(getLocalClassName(), "onStart");
    	db.open();
    }
    
    @Override
    public void onRestart() {
    	super.onRestart();
    	Log.d(getLocalClassName(), "onRestart");
    	db.open();
    }

    @Override
    protected void onDestroy() {
      super.onDestroy();
      Log.d(getLocalClassName(), "onDestroy");
      /*if ( this == home )
    	  db.close();*/
      
      tracker.dispatch();
      tracker.stop();
    }
    
    @Override
    protected void onPause() {
      super.onPause();
      Log.d(getLocalClassName(), "onPause");
      tracker.dispatch();
      tracker.stop();
    }	
    
    @Override
    protected void onStop() {
      super.onStop();
      Log.d(getLocalClassName(), "onStop");
    }	


    /**
     * Show a waiting popup
     */
    public void showWaitingMessage(){
    	try {
    		Log.d(getLocalClassName(), "show waiting message : "+waitingDialog);
    		if ( waitingDialog == null ) 
    			waitingDialog = new ProgressDialog(rootView.getContext());
			waitingDialog.setMessage(getResources().getString(R.string.home_waiting));
			waitingDialog.setIndeterminate(true);
			waitingDialog.setCancelable(false);
			waitingDialog.show();
		} catch (Exception e) {
			Log.e(getLocalClassName(), "showWaitingMessage : Error : ",e);
		}
    }
        
    /**
     * hide the waiting popup
     */
    public void hideWaitingMessage(){
    	try {
			if ( waitingDialog != null ) {
				Log.d(getLocalClassName(), "dismiss waiting message : "+waitingDialog);
				waitingDialog.dismiss();
				waitingDialog.cancel();
			}
		} catch (Exception e) {
			Log.e(getLocalClassName(), "hideWaitingMessage : Error : ",e);
		}
    }

    /**
     * Hide the waiting popup and show a Toast with argument value
     * @param ID
     */
    public void hideWaitingMessage(int ID){
    	hideWaitingMessage();
    	Toast.makeText(this, ID, Toast.LENGTH_SHORT).show();
    }
}